import React, {
    PureComponent
} from 'react';

import plugin, {
    parseData
} from './plugin';

interface User {
    loginUser: any
}

interface Props {
    user: User,
    children?:any
}

import * as Env from './../../env';

import * as CONST from './const';

import * as Token from './../../http/token';

import * as Event from './../../utils/event';

class Socket extends PureComponent<Props> {
    private connect: any = null;

    static defaultProps = {
        user:{}
    }

    public static CONST = CONST;
    public static on = Event.add;
    public static emit = Event.emit;

    //用户登录建立长连接
    private onUserLogin = async () => {
        this.onConnect();
    }

    private onConnect = async () => {
        const _para = {
                getToken: Token.get,
                url: await Env.socketUrl()
            }
        this.connect = (
            new plugin(_para)
        )
        this.connect.on(
            `message`,
            this.onListenMessage
        )
    }

    //销毁连接
    private onConnectClose = () => {
        if (!this.connect) {
            return false
        }
        this.connect.destroy()
        this.connect = null;
    }

    //用户登出监听
    private onUserLogOut = () => {
        this.onConnectClose();
    }

    private onListenMessage = ({data}: any) => {
        const {
            body,
            header
        } = parseData(data);
        const {
            type
        } = header;
        Event.emit(CONST[type as never], body);
    }

    UNSAFE_componentWillMount() {
        Event.add(Event.ON_USER_OUT, this.onUserLogOut);
        Event.add(Event.ON_USER_LOGIN, this.onUserLogin);
    }

    render() {
        const {
            children = null
        } = this.props;
        return children;
    }
}

export default Socket;